using AutoMapper;
using CMS.Entity;
using CMS.Service;
using CMS.Web.Attributes;
using CMS.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace CMS.Web.Controllers;

public class UserController(IUserService userService, IMapper mapper, IWebHostEnvironment webHostEnvironment) : Controller {
    public IActionResult Index() {
        return View();
    }

    public async Task<IActionResult> GetPagedUsers(int pageIndex, int pageSize, string userName, string userEmail) {
        var users = userService
            .GetPage(pageIndex + 1, pageSize, out int total, u => u.IsDeleted == false, u => u.Id, true);
        users = userService.GetSearchPage(new UserSearch(userName, userEmail), users);
        return Json(new { total, data = await users.ToListAsync() });
    }

    [HttpDelete]
    [UnitOfWork]
    public async Task<IActionResult> DeleteUsers(int[] userIds) {
        var users = await userService.Get(u => userIds.Contains(u.Id)).ToListAsync();
        foreach (User user in users) {
            user.IsDeleted = true;
            user.EditDate = DateTime.Now;
        }
        return Json(new { code = 200, msg = "删除成功" });
    }

    public IActionResult AddPage() {
        return View();
    }

    public async Task<IActionResult> PhotoUpload(IFormFile? photo) {
        if (photo == null) {
            return BadRequest("file not selected");
        }
        var fileName = Guid.NewGuid() + Path.GetExtension(photo.FileName);
        var filePath = Path.Combine(webHostEnvironment.ContentRootPath,"wwwroot","images",fileName);
        await using var stream = System.IO.File.Create(filePath);
        await photo.CopyToAsync(stream);
        return Json(new { code = 200, url = Path.Combine("images", fileName) });
    }

    [UnitOfWork]
    public async Task<IActionResult> AddUser([FromForm]User user) {
        user.IsDeleted = false;
        user.EditDate = DateTime.Now;
        user.CreatedDate = DateTime.Now;
        await userService.AddAsync(user);
        return Json(new { code=200,msg="添加信息成功"});
    }

    public async Task<IActionResult> EditPage(int? userId) {
        if (userId == null) {
            return BadRequest("user id is null");
        }
        User? user = await userService.Get(u => u.Id == userId).FirstOrDefaultAsync();
        if (user == null) {
            return BadRequest("user not found");
        }
        return View(user);
    }

    [UnitOfWork]
    public async Task<IActionResult> EditUser([FromForm]User user) {
        user.IsDeleted = false;
        user.EditDate = DateTime.Now;
        await userService.UpdateAsync(user);
        return Json(new { code = 200, msg = "更新成功" });
    }

    public async Task<IActionResult> ShowUsers() {
        var users = await userService.Get(u => u.IsDeleted == false).ToListAsync();
        var userDtos = mapper.Map<IList<User>, List<UserDto>>(users);
        return Json(userDtos);
    }
}